//
//  QJShopCarVC.m
//  QuanJieShopProject
//
//  Created by apple on 2018/1/30.
//  Copyright © 2018年 apple. All rights reserved.
//

#import "QJShopCarVC.h"
//数据为空的控件
#import "UIScrollView+EmptyDataSet.h"
#import "QJShopCarCell.h"
#import "QJShopCarBottomView.h"
//订单预览
#import "QJPreviewOrderVC.h"
#import "YFShopCarHeaderView.h"

@interface QJShopCarVC () <UITableViewDelegate,UITableViewDataSource,DZNEmptyDataSetDelegate,DZNEmptyDataSetSource>
@property (nonatomic, strong) UITableView *shopTableView;
//@property (nonatomic, strong) NSMutableArray *carArray;
@property (nonatomic, strong) QJShopCarBottomView *bottomView;

@property (nonatomic, strong) NSMutableArray *shopCarArr;

@property (nonatomic, strong) NSMutableArray *headerViewArr;

@end

@implementation QJShopCarVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    /*
     不透明的bar情况下,也进行视图延伸.
     在展示纯代码的scroll controller的时候,将navigationBar设置为不透明,又出现了这个问题
     比如:购物车--->登录--->返回tableview下移64
     */
    self.extendedLayoutIncludesOpaqueBars = YES;
    //解决表无故偏移
    self.automaticallyAdjustsScrollViewInsets = NO;
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(GoodsSelectOrDesSelectedNotification:) name:@"GoodsSelectOrDesSelectedNotification" object:nil];
      [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(ShopSelectedOrDesSelectedNotification:) name:@"ShopSelectedOrDesSelectedNotification" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(SelectAllOrDisSelecteAllNotification:) name:@"SelectAllOrDisSelecteAllNotification" object:nil];
    
}
- (void)SelectAllOrDisSelecteAllNotification:(NSNotification *)info{
    NSMutableDictionary *dic = info.object;
   
    [WWNetRequest fetchModifyShoppingCartAllStateWithParameters:dic success:^(id response) {
        NSLog(@"全选状态更新 response = %@", response);
        [self shopcarDataRequestAction];
    } failure:^(NSDictionary *error) {
        NSLog(@"全选状态更新 error = %@", error);
    }];
    
}
- (void)ShopSelectedOrDesSelectedNotification:(NSNotification *)info{
    NSDictionary *dict = info.object;
    [WWNetRequest fetchModifyShopSelectedStateWithParameters:dict success:^(id response) {
        NSLog(@"商铺状态更新 response = %@", response);
        [self shopcarDataRequestAction];
    } failure:^(NSDictionary *error) {
        NSLog(@"商铺状态更新 error = %@", error);
    }];
    
    
}
- (void)GoodsSelectOrDesSelectedNotification:(NSNotification *)info{
    NSDictionary *dic = info.object;
    [WWNetRequest fetchModifyGoodsSelectedStateWithParameters:dic success:^(id response) {
        [self shopcarDataRequestAction];
        NSLog(@"商品状态更新 response = %@", response);
    } failure:^(NSDictionary *error) {
        NSLog(@"商品状态更新 error = %@", error);
    }];
    
   
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.view addSubview:self.shopTableView];
    self.bottomView.selectState = QJShopCarBottomViewStateDisSelectAll;
    [self shopcarDataRequestAction];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
}
- (void)viewWillLayoutSubviews {
    
}

#pragma mark -- 数据请求方法
- (void)shopcarDataRequestAction{
    
    [WWNetRequest fetchCartListWithParameters:nil success:^(id response) {
        
         [self setupShopCarUIAction];
        NSLog(@"购物车列表 response = %@", response);
        NSDictionary *data = response[@"data"];
        NSArray *listArr = data[@"list"];
        
        NSMutableArray *tempShopCarArr = [NSMutableArray array];
        
        if (listArr.count == 0) {
            
            [self.bottomView removeFromSuperview];
            
            self.shopTableView.frame = CGRectMake(0, Height_NavBar, UISCREEN_WIDTH, UISCREEN_HEIGHT);
            
        }else{
           
            [self createBottomView];
            self.shopTableView.frame = CGRectMake(0, Height_NavBar, UISCREEN_WIDTH,UISCREEN_HEIGHT - Height_TabBar -50- Height_NavBar);
           
        }
        
        for (NSDictionary *dict in listArr) {
            YFShopCarModel *shopCarModel = [[YFShopCarModel alloc] initWithDictionary:dict error:nil];
            
            NSArray *shopArr = dict[@"cart_list"];  // 每个商铺
            NSMutableArray *tempArr = [NSMutableArray array];
            for (NSDictionary *shopDict in shopArr) {  // 每个商品
                ShopCarModel *model = [[ShopCarModel alloc]initWithDictionary:shopDict error:nil];
                model.image_url = shopDict[@"goods"][@"original_img"];
                NSLog(@"商品是否选中 model.ifSelect = %@", model.ifSelect);

                [tempArr addObject:model];
            }
            shopCarModel.goodArr = tempArr;
            [tempShopCarArr addObject:shopCarModel];
        }
        self.ShopCarArr = tempShopCarArr;
        
        [self.shopTableView reloadData];
       
        BOOL isSelectAll = YES;
        self.bottomView.selectState = QJShopCarBottomViewStateDisSelectAll;
        self.bottomView.selectedAllBtn.selected = NO;
        for (YFShopCarModel *shopCar in self.shopCarArr) {
                            for (ShopCarModel *model in shopCar.goodArr) {
                                if ([model.ifSelect isEqualToString:@"0"]) {
                                    isSelectAll = NO;
                                    break;
                                }
                            }
                        }
                        if (isSelectAll) {
                            self.bottomView.selectState = QJShopCarBottomViewStateSelectAll;
                            self.bottomView.selectedAllBtn.selected = YES;
                            
                        }
     
        [self calculateShopCarPriceAction];
    } failure:^(NSDictionary *error) {
      

        [self.shopTableView reloadData];
        [self calculateShopCarPriceAction];
    }];

}
#pragma mark -- 界面布局
- (void)setupShopCarUIAction{
    
    UIBarButtonItem *button = [[UIBarButtonItem alloc] initWithTitle:@"编辑" style:UIBarButtonItemStylePlain target:self action:@selector(rightBarClick)];
    button.tintColor = [UIColor whiteColor];
    self.navigationItem.rightBarButtonItem = button;
}

- (void)rightBarClick {
    
    if (self.bottomView.editState == QJShopCarBottomViewStateNormal) { // 编辑
        self.bottomView.editState = QJShopCarBottomViewStateEdit;
        self.navigationItem.rightBarButtonItem.title = @"完成";

    }else if (self.bottomView.editState == QJShopCarBottomViewStateEdit) { // 一般
        self.bottomView.editState = QJShopCarBottomViewStateNormal;
        self.navigationItem.rightBarButtonItem.title = @"编辑";
    }
}
#pragma mark -- UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.shopCarArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    YFShopCarModel *shopCar = self.shopCarArr[section];
    return shopCar.goodArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    // 获取数据源
    YFShopCarModel *shopCar = self.shopCarArr[indexPath.section];
    ShopCarModel *model = shopCar.goodArr[indexPath.row];
    
    // 给cell赋值
    QJShopCarCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellID" forIndexPath:indexPath];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell cellUpdateWithModel:model];
     WEAKSELF
    
    cell.shopNumberChangeBlock = ^(ShopCarModel *model){
        // 修改数据源
        [shopCar.goodArr replaceObjectAtIndex:indexPath.row withObject:model];
        [weakSelf calculateShopCarPriceAction];
        
    };
    
/*    cell.isSelect = [model.ifSelect isEqualToString:@"1"] ? YES : NO;
    WEAKSELF
 
//    cell.shopSelectOrNotBlock = ^(ShopCarModel *model) {
//
//        
//        [self shopcarDataRequestAction];
//        //*
//        // cell model数据源修改
////        [shopCar.goodArr replaceObjectAtIndex:indexPath.row withObject:model];
////        [weakSelf calculateShopCarPriceAction];
////        NSLog(@"ifSelect = %@", model.ifSelect);
////
////        if ([model.ifSelect isEqualToString:@"0"]) { // 判断全选按钮状态
////            // 一个取消,全选按钮就不选
////            self.bottomView.selectState = QJShopCarBottomViewStateDisSelectAll;
////            // 所在商铺页取消
////            shopCar.isSelect = @"0";
////
////            NSLog(@"section:%ld", indexPath.section);
////
////        }else {
////            // 全部勾选,全选按钮选中
////            BOOL isSelectAll = YES;
////
////            for (YFShopCarModel *shopCar in self.shopCarArr) {
////                for (ShopCarModel *model in shopCar.goodArr) {
////                    if ([model.ifSelect isEqualToString:@"0"]) {
////                        isSelectAll = NO;
////                        break;
////                    }
////                }
////            }
////
////            if (isSelectAll) {
////                self.bottomView.selectState = QJShopCarBottomViewStateSelectAll;
////            }
////        }
////        [self.shopTableView reloadData];
//    };*/
    return cell;
}
#pragma mark -- cell删除
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    return   UITableViewCellEditingStyleDelete;
}
//改变删除的文字
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
    return @"删除";
}
//删除函数
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [self deleteShopActionWithTableView:tableView andIndexPath:indexPath];
    }
}
#pragma mark -- UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 120;
}

// 设置表头的高度。如果使用自定义表头，该方法必须要实现，否则自定义表头无法执行，也不会报错
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 40;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {

    YFShopCarModel *shopCarModel = self.shopCarArr[section];
    
    BOOL isSelected = YES;
    // 判断店铺是否选中 goodArr
    for (ShopCarModel *model in shopCarModel.goodArr) {
        if ([model.ifSelect isEqualToString:@"0"]) {
            isSelected = NO;
            break;
        }
    }
    shopCarModel.isSelect = isSelected ? @"1" : @"0";
    
    YFShopCarHeaderView *headerView = [[YFShopCarHeaderView alloc] initWithFrame:CGRectMake(0, 0, UISCREEN_WIDTH, 40)];
    headerView.model = shopCarModel;
    headerView.selectedButtonClickBlock = ^(BOOL isSelect) {
        
        shopCarModel.isSelect = isSelect ? @"1" : @"0";
        
        int __block index = 0;
        for (int i = 0; i<shopCarModel.goodArr.count; i++) {
            ShopCarModel *goodModel = shopCarModel.goodArr[i];
            goodModel.ifSelect = isSelect ? @"1" : @"0";
            if ([goodModel.ifSelect isEqualToString:@"1"]) {
                NSMutableDictionary *dict = [NSMutableDictionary dictionary];
                [dict setObject:goodModel.goodsid forKey:@"id"];
                [dict setObject:goodModel.ifSelect forKey:@"selected"];
                NSLog(@"dict = %@", dict);
                [WWNetRequest fetchModifyGoodsSelectedStateWithParameters:dict success:^(id response) {
                    NSLog(@"商品状态更新 response = %@", response);
                    index ++;
                    if (index == i) {
                        
                        [self shopcarDataRequestAction];
                    }
                } failure:^(NSDictionary *error) {
                    NSLog(@"商品状态更新 error = %@", error);
                }];
            }
        }
       
    };
    
    // 店铺的名字一样的就不加了,这里加个判断
//    [self.headerViewArr addObject:headerView];
    return headerView;
}


#pragma mark -- DZNEmptyDataSetSource
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView
{
    return [UIImage imageNamed:@"noDataImage"];
}
#pragma mark -- DZNEmptyDataSetDelegate
- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView{
    return YES;
}
#pragma mark -- 结算方法
- (void)calculateShopCarPriceAction{ // 计算总额
    CGFloat totalPrice = 0.00;
    
    for (YFShopCarModel *shopCar in self.shopCarArr) {
        for (ShopCarModel *model in shopCar.goodArr) {
            NSLog(@"model.ifSelect = %@", model.ifSelect);
            NSString *selectStr = [NSString stringWithoutNilFormart:model.ifSelect];
            if ([selectStr isEqualToString:@"1"]) {
                NSInteger amount = [model.amount integerValue];
                NSLog(@"amount = %ld", amount);
                CGFloat singlePrice = [model.price floatValue];
                totalPrice = totalPrice + amount * singlePrice;
            }
        }
    }
    
    
//    for (int i = 0; i < self.carArray.count; i++) {
//        ShopCarModel *model = self.carArray[i];
//        NSString *selectStr = [NSString stringWithoutNilFormart:model.ifSelect];
//        if ([selectStr isEqualToString:@"1"]) {
//            NSInteger amount = [model.amount integerValue];
//            CGFloat singlePrice = [model.price floatValue];
//            totalPrice = totalPrice + amount * singlePrice;
//        }
//    }
    [self.bottomView bottomViewUpdateDataWithPrice:totalPrice];
}
#pragma mark -- 删除购物车方法
- (void)deleteShopActionWithTableView:(UITableView *)tableView andIndexPath:(NSIndexPath *)indexPath{

    YFShopCarModel *shopCar = self.shopCarArr[indexPath.section];
    ShopCarModel *model = shopCar.goodArr[indexPath.row];

    [self deleteShopActionWithArr:@[model]];
}

// 对数组模型的id进行字符串拼接, 方便网络请求
- (NSString *)handleRequestStrWithArr:(NSArray <ShopCarModel*>*)arr {
    NSString *str = @"";
    for (int i = 0; i < arr.count; i++) {
        ShopCarModel *model = arr[i];
        if (i == 0) {
            str = [str stringByAppendingString:model.id];
        }else {
            str = [str stringByAppendingString:[NSString stringWithFormat:@",%@", model.id]];
        }
    }
    NSLog(@"str = %@", str);
    return str;
}

- (void)deleteShopActionWithArr:(NSArray <ShopCarModel*>*)arr {
    NSString *shopId = [self handleRequestStrWithArr:arr];
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:shopId forKey:@"cart_ids"];
    
    [WWNetRequest fetchDeleteCartWithParameters:dict success:^(id response) {
        if (response) {
            NSLog(@"====== 删除成功");
            NSMutableArray *tempShopCarArr = [NSMutableArray arrayWithArray:self.shopCarArr];
            
            // 不删除数据源了,直接重新请求网络
            for (ShopCarModel *deleteModel in arr) {

                // 删除商铺里的商品
                for (YFShopCarModel *shopCar in self.shopCarArr) {

                    NSMutableArray *tempGoodsArr = [NSMutableArray arrayWithArray:shopCar.goodArr];
                    for (ShopCarModel *model in shopCar.goodArr) {
                        if ([model.goodsid isEqualToString:deleteModel.goodsid]) {
                            [tempGoodsArr removeObject:model];
                        }
                    }
                    shopCar.goodArr = tempGoodsArr;
                    
                    // 如果商铺里商品都没有, 那么清空商铺
                    if (tempGoodsArr.count == 0) {
                        [tempShopCarArr removeObject:shopCar];
                    }
                }
            }
            
            
            self.shopCarArr = tempShopCarArr;
            // 删除对应的cell
            [self shopcarDataRequestAction];

        }
    } failure:^(NSDictionary *error) {
        NSLog(@"删除错误信息 = %@", error);
    }];
}


#pragma mark -- 懒加载
- (UITableView *)shopTableView{
    if (!_shopTableView) {
      
        self.shopTableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
        [self.view addSubview:self.shopTableView];
        self.shopTableView.delegate = self;
        self.shopTableView.dataSource = self;
        self.shopTableView.emptyDataSetDelegate = self;
        self.shopTableView.emptyDataSetSource = self;
        self.shopTableView.backgroundColor = HexRGB(0xf5f5f5);
        self.shopTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        //注册cell
        [self.shopTableView registerNib:[UINib nibWithNibName:@"QJShopCarCell" bundle:nil] forCellReuseIdentifier:@"cellID"];
    }
    return _shopTableView;
}

- (void)createBottomView {
  
        CGFloat height = 50;
    if (_bottomView == nil) {
         _bottomView = [[QJShopCarBottomView alloc] initWithFrame: CGRectMake(0, UISCREEN_HEIGHT - height - Height_TabBar, UISCREEN_WIDTH, height)];
    }
    
        [self.view addSubview:_bottomView];
        WEAKSELF

        _bottomView.payBtnClickBlock = ^{
            
            if (_bottomView.editState == QJShopCarBottomViewStateNormal) { // 结算

                NSMutableArray *selectedArr = [weakSelf selectedArr];
                NSString *shopIDStr = [weakSelf handleRequestStrWithArr:selectedArr];
               
                QJPreviewOrderVC *VC = [[QJPreviewOrderVC alloc]init];
                VC.orderType = @"1";
                VC.orderCarid = shopIDStr;
                NSLog(@"shopIDStr = %@", shopIDStr);
                if (selectedArr.count == 0) {
                    [MBPHUD showAlertWithTitle:@"请选择要结算的商品!"];
                }else{
                    [weakSelf.navigationController pushViewController:VC animated:YES];
                }
            }else if (weakSelf.bottomView.editState == QJShopCarBottomViewStateEdit) { // 删除
                NSMutableArray *selectedArr = [weakSelf selectedArr];
                
                UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"确定删除所有购物车商品?"
                                                                               message:@""
                                                                        preferredStyle:UIAlertControllerStyleAlert];
                
                UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault
                                                                      handler:^(UIAlertAction * action) {
                                                                          
                                                                           [weakSelf deleteShopActionWithArr:selectedArr];
                                                                      }];
                UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault
                                                                     handler:^(UIAlertAction * action) {
                                                                        
                                                                     }];
                
                [alert addAction:defaultAction];
                [alert addAction:cancelAction];
                [weakSelf presentViewController:alert animated:YES completion:nil];
                
               
                
            }
        };
        
        
        // 全选
        self.bottomView.selectedAllBlock = ^(BOOL isSelect) {
            for (YFShopCarModel *shopCar in weakSelf.shopCarArr) {
                shopCar.isSelect = isSelect ? @"1" : @"0";
                for (ShopCarModel *model in shopCar.goodArr) {
                     model.ifSelect = isSelect ? @"1" : @"0";
                }
            }

            [weakSelf.shopTableView reloadData];
            [weakSelf calculateShopCarPriceAction];
            
            
            // 网络请求全选
            NSMutableDictionary *dict = [NSMutableDictionary dictionary];
            NSString *selectedStr = isSelect ? @"1" : @"0";
            [dict setObject:selectedStr forKey:@"selected"];
            
            [WWNetRequest fetchModifyShoppingCartAllStateWithParameters:dict success:^(id response) {
                NSLog(@"全选状态更新 response = %@", response);
            } failure:^(NSDictionary *error) {
                NSLog(@"全选状态更新 error = %@", error);
            }];
            
        };
}
//- (NSMutableArray *)carArray{
//    if (!_carArray) {
//        _carArray = [NSMutableArray array];
//    }
//    return _carArray;
//}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

// 获取当前选中项数组
- (NSMutableArray *)selectedArr {
    NSMutableArray *tempArr = [NSMutableArray array];
    
    for (YFShopCarModel *shopCar in self.shopCarArr) {
        for (ShopCarModel *model in shopCar.goodArr) {
            if ([model.ifSelect isEqualToString:@"1"]) {
                [tempArr addObject:model];
            }
        }
    }
    return tempArr;
}

- (NSMutableArray *)headerViewArr {
    if (!_headerViewArr) {
        _headerViewArr = [NSMutableArray array];
    }
    return _headerViewArr;
}

- (void)testPrintState {
    for (YFShopCarModel *shopCar in self.shopCarArr) {
        NSLog(@"店铺选中状态= %@", shopCar.isSelect);
        for (ShopCarModel *model in shopCar.goodArr) {
            NSLog(@"商品选中状态= %@", model.ifSelect);
            
        }
    }
}


@end
